Expand description
map-macro
This crate offers declarative macros for initializing collections from the standard library.
This crate has zero dependencies.
Example
use map_macro::hash_map;
let hello = hash_map! {
"en" => "Hello",
"de" => "Hallo",
"fr" => "Bonjour",
"es" => "Hola",
};
Explicitly Typed Values for Trait Objects
As shown in the example above, the compiler uses type inference to infer the correct type for the created map. Unfortunately, type inference alone can not detect trait objects. This will not work, because the compiler is unable to figure out the right type:
use std::collections::HashMap;
use std::fmt::Debug;
use map_macro::hash_map;
let hello: HashMap<&str, &dyn Debug> = hash_map! {
"en" => &"Hello",
"de" => &"Hallo",
"fr" => &"Bonjour",
"es" => &"Hola",
};
The map_e!
macro enables you to use trait objects as values through
type coercion, making the example above compile successfully:
use std::collections::HashMap;
use std::fmt::Debug;
use map_macro::hash_map_e;
let hello: HashMap<&str, &dyn Debug> = hash_map_e! {
"en" => &"Hello",
"de" => &"Hallo",
"fr" => &"Bonjour",
"es" => &"Hola",
};
Note that you need to give an explicit type to the binding when you use map_e!
, because
it relies on knowing what type it should coerce the values to.
Also, only values and not keys can be trait objects, because keys must
implement the Hash
trait, which is not
object safe.
Where the trait bounds on generic type parameters of the collections allow trait objects,
macros for explicitly typed variants are provided.
The explicitly typed versions of the macros are indicated by an _e
suffix.
Macros
- Macro for creating a
BinaryHeap
. - Macro for creating a
BTreeMap
. - Explicitly typed equivalent of
btree_map!
, suitable for trait object values. - Macro for creating a
BTreeSet
. - Macro for creating a
HashMap
. - Explicitly typed equivalent of
hash_map!
, suitable for trait object values. - Macro for creating a
HashSet
. - Macro for creating a
LinkedList
. - Explicitly typed equivalent of
linked_list!
, suitable for trait object values. - mapDeprecatedDeprecated. Use
hash_map!
instead. - map_eDeprecatedDeprecated. Use
hash_map_e!
instead. - setDeprecatedDeprecated. Use
hash_set!
instead. - Macro for creating a
VecDeque
. - Explicitly typed equivalent of
vec_deque!
, suitable for trait object values.